package com.xindacloud.sms.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xindacloud.sms.portal.dao.SmsSubmissionRecordMapper;
import com.xindacloud.sms.portal.dao.SmsUserMapper;
import com.xindacloud.sms.portal.dto.SearchMessageDTO;
import com.xindacloud.sms.portal.dto.SmsDashBoardReportDTO;
import com.xindacloud.sms.portal.dto.SmsSubmissionRecordDTO;
import com.xindacloud.sms.portal.dto.SmsTotalDashBoardReportDTO;
import com.xindacloud.sms.portal.entity.SmsAgent;
import com.xindacloud.sms.portal.entity.SmsSubmissionRecord;
import com.xindacloud.sms.portal.entity.SmsUser;
import com.xindacloud.sms.portal.exception.ServiceException;
import com.xindacloud.sms.portal.service.ISmsAgentService;
import com.xindacloud.sms.portal.service.ISmsSubmissionRecordService;
import com.xindacloud.sms.portal.utils.DateUtils;
import com.xindacloud.sms.portal.utils.UnionResultHelp;
import com.xindacloud.sms.portal.vo.SearchMessageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SmsSubmissionRecordServiceImpl extends ServiceImpl<SmsSubmissionRecordMapper, SmsSubmissionRecord> implements ISmsSubmissionRecordService {

    private final CommonServiceImpl commonService;

    private final ISmsAgentService smsAgentService;

    @Autowired
    public SmsSubmissionRecordServiceImpl(CommonServiceImpl commonService, ISmsAgentService smsAgentService) {
        this.commonService = commonService;
        this.smsAgentService = smsAgentService;
    }

    @Override
    public IPage<SearchMessageVO> searchMessage(SearchMessageDTO searchMessageDTO) {

        final int userId;
        try {
            userId = Integer.parseInt(searchMessageDTO.getUserId());
        } catch (NumberFormatException e) {
            throw new ServiceException("无效的用户ID", UnionResultHelp.StatusEnum.ParamsFail.code());
        }

        List<Integer> userIds = commonService.queryUserIdsFor(userId);
        if (CollectionUtils.isEmpty(userIds)) {
            return null;
        }

        final String messageIds = searchMessageDTO.getMessageIds();
        List<String> messageIdList = null;
        if (StringUtils.isNotEmpty(messageIds)) {
            messageIdList = Arrays.asList(messageIds.trim().split(","));
        }
        if (Objects.equals("all", searchMessageDTO.getStatus().toLowerCase())) {
            searchMessageDTO.setStatus("");
        }
        if (Objects.equals(searchMessageDTO.getStartDate(), null)) {
            searchMessageDTO.setStartDate("");
        }
        if (Objects.equals(searchMessageDTO.getEndDate(), null)) {
            searchMessageDTO.setEndDate("");
        }
        final IPage<SmsSubmissionRecord> smsSubmissionRecordIPage = lambdaQuery()
                /* .in(CollectionUtils.isNotEmpty(messageIdList),
                         SmsSubmissionRecord::getMessageId, messageIdList)*/
                .in(CollectionUtils.isNotEmpty(messageIdList),
                        SmsSubmissionRecord::getTaskId, messageIdList)
                .in(CollectionUtils.isNotEmpty(userIds),
                        SmsSubmissionRecord::getUserId, userIds)
                .eq(StringUtils.isNotEmpty(searchMessageDTO.getStatus()), SmsSubmissionRecord::getFinalStatus, searchMessageDTO.getStatus())
                .eq(StringUtils.isNotEmpty(searchMessageDTO.getTo()), SmsSubmissionRecord::getSendTo, searchMessageDTO.getTo())
                /*.or(StringUtils.isNotEmpty(searchMessageDTO.getTo()), queryWrapper ->
                        queryWrapper.eq(SmsSubmissionRecord::getSendTo, searchMessageDTO.getTo()))
                .or(StringUtils.isNotEmpty(searchMessageDTO.getTo()), queryWrapper ->
                        queryWrapper.eq(SmsSubmissionRecord::getSendTo, "00".concat(searchMessageDTO.getTo())))*/
                .ge(StringUtils.isNotEmpty(searchMessageDTO.getStartDate()), SmsSubmissionRecord::getSubmitTime,
                        searchMessageDTO.getStartDate().concat(" ").concat("00:00:00"))
                .le(StringUtils.isNotEmpty(searchMessageDTO.getEndDate()), SmsSubmissionRecord::getSubmitTime,
                        searchMessageDTO.getEndDate().concat(" ").concat("23:59:59"))
                .orderByDesc(SmsSubmissionRecord::getSubmitTime)
                .page(new Page<>(searchMessageDTO.getCurrentPage(), searchMessageDTO.getPageSize()));

        final Map<String, SmsAgent> agentMap = smsAgentService.queryAllAgent()
                .stream()
                .collect(Collectors.toMap(SmsAgent::getAgentId, Function.identity(), (key1, key2) -> key2));

        return smsSubmissionRecordIPage.convert(smsSubmissionRecord -> {
            SearchMessageVO searchMessageVO = new SearchMessageVO();
            BeanUtils.copyProperties(smsSubmissionRecord, searchMessageVO);
            searchMessageVO.setAgentName(getAgentName(agentMap, smsSubmissionRecord));
            return searchMessageVO;
        });

    }

    private String getAgentName(Map<String, SmsAgent> agentMap, SmsSubmissionRecord smsSubmissionRecord) {
        if (CollectionUtils.isNotEmpty(agentMap)) {
            final SmsAgent smsAgent = agentMap.get(smsSubmissionRecord.getAgentId());
            if (Objects.nonNull(smsAgent)) {
                return smsAgent.getAgentName();
            }
        }
        return "Unknown";

    }


    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    SmsSubmissionRecordMapper smsSubmissionRecordMapper;

    @Override
    public Object getSmsDashBoardList(SmsSubmissionRecordDTO smsSubmissionRecordDTO) {
        //Page<SmsSubmissionRecord> page=new Page<>(smsSubmissionRecordDTO.getPageNum(),smsSubmissionRecordDTO.getPageSize());
        if (smsSubmissionRecordDTO.getDuration().equals("week")) {
            smsSubmissionRecordDTO.setStime(DateUtils.getBeginDayOfWeek());
            smsSubmissionRecordDTO.setEtime(DateUtils.getEndDayOfWeek());
        } else if (smsSubmissionRecordDTO.getDuration().equals("month")) {
            smsSubmissionRecordDTO.setStime(DateUtils.getBeginDayOfMonth());
            smsSubmissionRecordDTO.setEtime(DateUtils.getEndDayOfMonth());
        } else if (smsSubmissionRecordDTO.getDuration().equals("quarter")) {
            smsSubmissionRecordDTO.setStime(DateUtils.getCurrentQuarterStartTime());
            smsSubmissionRecordDTO.setEtime(DateUtils.getCurrentQuarterEndTime());
        } else if (smsSubmissionRecordDTO.getDuration().equals("year")) {
            smsSubmissionRecordDTO.setStime(DateUtils.getBeginDayOfYear());
            smsSubmissionRecordDTO.setEtime(DateUtils.getEndDayOfYear());
        } else if (smsSubmissionRecordDTO.getDuration().equals("day")) {
            smsSubmissionRecordDTO.setStime(DateUtils.getDayBegin());
            smsSubmissionRecordDTO.setEtime(DateUtils.getDayEnd());
        }
		/*Set<Integer> userIds=getUserIds(smsSubmissionRecordDTO.getUserId());
		smsSubmissionRecordDTO.setUserIds(userIds);*/
        List<SmsDashBoardReportDTO> dbReport = smsSubmissionRecordMapper.getSmsDashBoardReport(smsSubmissionRecordDTO);
        SmsDashBoardReportDTO totalRecord = smsSubmissionRecordMapper.getTotalSmsDashBoardReport(smsSubmissionRecordDTO);
        SmsTotalDashBoardReportDTO smsTotalDashBoardReportDTO = new SmsTotalDashBoardReportDTO();
        smsTotalDashBoardReportDTO.setDashBoardReport(dbReport);
        smsTotalDashBoardReportDTO.setTotalDashBoardReport(totalRecord);
        return smsTotalDashBoardReportDTO;
    }

    @Autowired
    private SmsUserMapper smsUserMapper;

    Set<Integer> idsList = new HashSet<>();

    public Set<Integer> getUserIds(Integer userId) {
        QueryWrapper<SmsUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_user_id", userId);
        List<SmsUser> smsUsers = smsUserMapper.selectList(queryWrapper);
        if (smsUsers != null) {
            idsList.add(userId);
            for (SmsUser smsUser : smsUsers) {
                getUserIds(smsUser.getUserId());
            }
        }
        return idsList;

    }


    @Override
    public SmsSubmissionRecord querySmsSubmissionRecord(SmsSubmissionRecord smsSubmissionRecord) {
        return lambdaQuery()
                .eq(SmsSubmissionRecord::getSendTo, smsSubmissionRecord.getSendTo())
                .eq(SmsSubmissionRecord::getTaskId, smsSubmissionRecord.getTaskId())
                .eq(SmsSubmissionRecord::getUserId, smsSubmissionRecord.getUserId())
                .one();
    }

    @Override
    public boolean insertBatch(Collection<SmsSubmissionRecord> entityList) {
        return saveBatch(entityList);
    }


}
